<template>
  <div id="Fix">
    <img src="../../../static/m_img/h_x_xz.png" alt>
    <img src="../../../static/m_img/h_x_zd.png" alt @click="scrollToTop" v-show='toTopShow'>
  </div>
</template> 
<script>
export default {
  data() {
    return {
        toTopShow:false
    };
  },
  methods: {
    handleScroll() {
      //首先修改相对滚动位置
      this.scrollTop = this.scrollTop =
        window.pageYOffset || document.body.scrollTop;
      if (this.scrollTop > 300) {
        this.toTopShow = true;
      } else {
        this.toTopShow = false;
      }
    },
    scrollToTop() {
      let timer = null,
        _that = this;
      //动画，使用requestAnimationFrame代替setInterval
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        if (_that.scrollTop > 0) {
          _that.scrollTop -= 50;
          //然后修改这里实现动画滚动效果
          document.body.scrollTop = document.documentElement.scrollTop =
            _that.scrollTop;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
          _that.toTopShow = false;
        }
      });
    }
  },
  mounted() {
    this.$nextTick(function() {
      //修改事件监听
      window.addEventListener("scroll", this.handleScroll);
    });
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  }
};
</script>
<style  scoped lang='scss'>
#Fix {
  position: fixed;
  bottom: 0px;
  right: 5px;
  width: 50px;
  img {
    width: 47px;
    height: 47px;
  }
  img:first-child() {
    margin-bottom: 14.5px;
  }
}
</style>
